﻿namespace PowerSong.Projection
    {
    using System;
    using System.Collections.Generic;
    using System.Windows.Controls;

    public class ProjectorSet
        {

        private List<Projector> projectors = new List<Projector>();

        public Projector[] AllProjectors
            {
            get { return projectors.ToArray(); }
            }

        public Projector CreateControlProjector(Grid grid)
            {

            // Create a new manager
            var projector = new Projector(grid, null);
            projectors.Add(projector);

            // Return the manager
            return projector;

            }

        public Projector CreateWindowProjector(bool showImmediately)
            {

            // Create a new manager (and show the window immediately if required)
            var window = new ProjectorWindow(this);
            if (showImmediately) window.Show();

            // Return the manager
            projectors.Add(window.Projector);
            return window.Projector;

            }

        public Projector CloneToControl(Projector projector, Grid targetControl)
            {
            var newManager = new Projector(targetControl, null);
            projector.CopyTo(newManager);
            projectors.Add(newManager);
            return newManager;
            }

        public Projector CloneToWindow(Projector projector)
            {
            var window = new ProjectorWindow(this);
            window.Show();
            projector.CopyTo(window.Projector);
            projectors.Add(window.Projector);
            return window.Projector;
            }

        public void RemoveAllProjectors()
            {
            foreach (var manager in projectors.ToArray())
                {
                RemoveProjector(manager);
                }
            }

        public void RemoveProjector(Projector manager)
            {
            RemoveProjectorInternal(manager, false);
            }

        internal void RemoveProjectorInternal(Projector manager, bool windowBeingClosedByUser)
            {

            // Check that the manager is controlled by this class
            if (!projectors.Contains(manager))
                {
                throw new Exception("The given projector manager is not controlled by this projection manager.");
                }

            // Clear the contents of the hosted control
            manager.Clear();

            // Delete the window if the manager is hosted by a window
            if (manager.Window != null)
                {
                if (!windowBeingClosedByUser) manager.Window.Close();
                manager.Window = null;
                }

            // Remove the manager from the list
            projectors.Remove(manager);

            }

        }

    }
